/*
 * Description: Control the behavior of applications within Windows.
*/

#include "app_controller.h"
#include "performance/utils/perf_utils.h"

namespace APPCONTROLLER {

const DWORD FORBIDDEN_SCREEN_SAVER_POPUP = 0;
const DWORD NOT_MODIFY_SCREEN_SAVER_POPUP = 0;
const DWORD MODIFIED_SCREEN_SAVER_POPUP = 1;

bool OnStartupBaoFeng()
{
    std::string userSid = PERF_UTILS.GetCurrentUserSid();
    if (userSid == "") {
        LOG_WARN("[APPCONTROLLER - OnStartupBaoFeng] - get user sid failed");
        return false;
    }

    std::string stormPlayerKey = userSid + R"(\Software\Baofeng\StormPlayer)";
    std::string stormPlayerUserConfigKey = R"(UserConfig)";
    const std::string ScreenSaverPopupItemKey = "EnableScreenSaverPopup";
    const std::string ModifiedScreenSaverPopupItemKey = "ModifiedScreenSaverPopup";
    const DWORD ScreenSaverPopupItemValue = FORBIDDEN_SCREEN_SAVER_POPUP;
    DWORD ModifiedScreenSaverPopupItemValue = NOT_MODIFY_SCREEN_SAVER_POPUP;
    HKEY hKey = nullptr;

    if (!REGISTRY_UTILS.GetRegKey(HKEY_USERS, stormPlayerKey.c_str(), hKey) || hKey == nullptr) {
        LOG_ERR("[APPCONTROLLER - OnStartupBaoFeng] - get baofeng hKey failed");
        return false;
    }

    if (!REGISTRY_UTILS.QueryRegDWORD(hKey, stormPlayerUserConfigKey.c_str(),
        ModifiedScreenSaverPopupItemKey.c_str(), ModifiedScreenSaverPopupItemValue)) {
        LOG_ERR("[APPCONTROLLER - OnStartupBaoFeng] - QueryReg ModifiedScreenSaverPopupItemKey failed");
        return false;
    } else if (ModifiedScreenSaverPopupItemValue == MODIFIED_SCREEN_SAVER_POPUP) {
        return true;
    }

    if (!(REGISTRY_UTILS.SetRegDWORD(hKey, stormPlayerUserConfigKey.c_str(),
        ModifiedScreenSaverPopupItemKey.c_str(), MODIFIED_SCREEN_SAVER_POPUP))) {
        LOG_ERR("[APPCONTROLLER - OnStartupBaoFeng] - set baofeng ScreenSaverPopup flag failed");
        return false;
    }

    bool res = REGISTRY_UTILS.SetRegDWORD(hKey, stormPlayerUserConfigKey.c_str(),
        ScreenSaverPopupItemKey.c_str(), ScreenSaverPopupItemValue);
    REGISTRY_UTILS.SafeCloseHKey(hKey);
    return res;
}

using AppControllerFunc = bool(*)();
const std::map<std::string, AppControllerFunc> ONSTARTUPAPPTABLE = {
    {"BaofengPlatform.exe", &OnStartupBaoFeng},
};

void AppController::OnStartup(const std::string &processName)
{
    auto iter = ONSTARTUPAPPTABLE.find(processName);
    if (iter != ONSTARTUPAPPTABLE.end()) {
        auto func = iter->second;
        if (!func()) {
            LOG_ERR("OnStartup execute function failed, processName = {}", processName.c_str());
        }
    }
}

} // namespace APPCONTROLLER